import { getAstDataBoardInfoApi } from '@/controllers/API/assistant'
import { useEffect, useState } from 'react'
import ActiveUserChart from './charts/ActiveUserChart'
import HistoricalUsersChart from './charts/HistoricalUsersChart'
import RetentionRateChart from './charts/RetentionRateChart'
import SessionCountChart from './charts/SessionCountChart'
import SessionTurnChart from './charts/SessionTurnChart'
import './index.less'
import { ConditionsType } from './types'
import { formatCondition, getArrayResult } from './utils'

const DataBoardMain = ({
  condition,
  setCountDate
}: {
  condition: ConditionsType
  setCountDate: (date: string) => void
}) => {
  const [loading, setLoading] = useState(false)
  const [dataInfo, setDataInfo] = useState({
    xData: [],
    activeUsersCount: [],
    nextDayRetention: [],
    sevenDayRetention: [],
    fifteenDayRetention: [],
    sessionsCount: [],
    sessionTurnCount: [],
    historicalUsersCount: []
  })

  useEffect(() => {
    // 看后端所有图表给一个接口，还是每个图表一个接口，如果只有一个接口请求放最外层
    setLoading(true)
    console.log('ActiveUserChart condition', condition)
    const params = formatCondition(condition)
    getAstDataBoardInfoApi(params)
      .then((res: any) => {
        console.log('getAstDataBoardInfoApi res', res)
        setCountDate(res?.dashboard_count_date)
        setDataInfo({
          xData: getArrayResult(res?.xData),
          activeUsersCount: getArrayResult(res?.activeUsersCount),
          nextDayRetention: getArrayResult(res?.nextDayRetention),
          sevenDayRetention: getArrayResult(res?.sevenDayRetention),
          fifteenDayRetention: getArrayResult(res?.fifteenDayRetention),
          sessionsCount: getArrayResult(res?.sessionsCount),
          sessionTurnCount: getArrayResult(res?.sessionTurnCount),
          historicalUsersCount: getArrayResult(res?.historicalUsersCount)
        })
        setLoading(false)
      })
      .finally(() => {
        setLoading(false)
      })
  }, [condition])
  return (
    <div className="board-main scrollbar-hide">
      {/* 活跃用户数 */}
      <ActiveUserChart condition={condition} dataInfo={dataInfo} loading={loading} />

      {/* 缓存率 */}
      <RetentionRateChart condition={condition} dataInfo={dataInfo} loading={loading} />

      {/* 会话次数 */}
      <SessionCountChart condition={condition} dataInfo={dataInfo} loading={loading} />

      {/* 会话轮次 */}
      <SessionTurnChart condition={condition} dataInfo={dataInfo} loading={loading} />

      {/* 历史使用人数 */}
      <HistoricalUsersChart condition={condition} dataInfo={dataInfo} loading={loading} />
    </div>
  )
}

export default DataBoardMain
